package com.weai.config;

import com.weai.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * 安全配置
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    
    /**
     * 配置安全过滤器链
     *
     * @param http HttpSecurity
     * @return SecurityFilterChain
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .csrf().disable()
                .authorizeHttpRequests(authorize -> authorize
                // 静态资源和前端路由访问权限配置
                .requestMatchers(
                    // 静态资源
                    "/",
                    "/index.html", 
                    "/*.js", 
                    "/*.css", 
                    "/*.svg", 
                    "/favicon.ico",
                    "/*.chunk.css",
                    "/*.async.js",
                    "/static/**",
                    
                    // 前端路由路径 - 允许所有非api路径
                    "/{path:^(?!api).*$}/**"
                ).permitAll()
                        // 公开端点
                        .requestMatchers("/api/users/register", "/api/users/login").permitAll()
                        .requestMatchers("/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
                        // 对于GET方法，允许匿名访问
                        .requestMatchers(HttpMethod.GET, "/api/users/**").permitAll()
                        // 允许所有任务相关的GET请求
                        .requestMatchers(HttpMethod.GET, "/api/tasks/**").authenticated()
                        // 允许存款AI助手接口
                        .requestMatchers("/api/depositai/chat").authenticated()
                        // 允许企业微信AI服务助手接口
                        .requestMatchers(HttpMethod.POST, "/api/depositai/wechat").permitAll()
                        .requestMatchers("/api/solutions").permitAll()
                        .requestMatchers("/api/ailist").permitAll()
                        .requestMatchers("/api/aipapers").permitAll()
                        .requestMatchers("/api/aibooks").permitAll()
                        .requestMatchers("/api/taskreport/*").permitAll()
                        .requestMatchers("/api/taskreport").permitAll()
                        .requestMatchers("/api/tasks/overview").permitAll()
                        // 其他请求需要认证
                        .anyRequest().authenticated()
                )
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
    
    /**
     * 配置密码编码器
     *
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 配置认证管理器
     *
     * @param config 认证配置
     * @return AuthenticationManager
     * @throws Exception 异常
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
    
    /**
     * 配置CORS
     *
     * @return CorsConfigurationSource
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许的前端源，包括常见的开发端口
        configuration.setAllowedOrigins(Arrays.asList(
                "http://localhost:8080", 
                "http://localhost:8000", 
                "http://localhost:8001", 
                "http://localhost:8002",
                "http://localhost:8003",
                "http://localhost:3000",
                "http://127.0.0.1:8000", 
                "http://127.0.0.1:8001", 
                "http://127.0.0.1:8002",
                "http://127.0.0.1:8003",
                "http://127.0.0.1:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Auth-Token"));
        configuration.setExposedHeaders(Arrays.asList("X-Auth-Token"));
        // 允许携带认证信息
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
} 